package com.sat.order.listener;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.sat.goods.config.SkuFeign;
import com.sat.order.config.OrderRabbitMqConfig;
import com.sat.order.mapper.OrderItemMapper;
import com.sat.order.mapper.OrderMapper;
import com.sat.order.model.Order;
import com.sat.order.model.OrderItem;
import com.sat.order.service.OrderService;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 监听pay_queue队列
 */
@Component
class PayRabbitMqListener {

    @Autowired
    private OrderService orderService;
    @RabbitListener(queues ="pay_queue")
    public void getMsg(Message message,Channel channel) throws Exception {
        //从队列获取到的数据是字节数组
        byte[] body = message.getBody();
        String payDataJson = new String(body);
        ObjectMapper mapper = new ObjectMapper();
        Map<String,String> map = mapper.readValue(payDataJson, Map.class);
        //获取微信消息发送状态
        String return_code = map.get("return_code");
        //判断微信支付消息是否发送成功
        if ("SUCCESS".equals(return_code)){
            //在判断支付业务是否成功
            if ("SUCCESS".equals(map.get("result_code"))){
                //到这里才表示支付成功
                //获取系统订单号
                //获取支付流水号，或者是支付id，这个是保存在支付公司的

                //获取商户订单号
                String out_trade_no = map.get("out_trade_no");
                //获取流水号，或者叫微信订单号
                String transaction_id = map.get("transaction_id");


                //获取支付完成时间
                String time_end = map.get("time_end");

                //根据订单id，将数据保存到数据库
                Order order = new Order();
                order.setId(out_trade_no);
                order.setTransactionId(transaction_id);
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
                Date date = sdf.parse(time_end);
                order.setPayTime(date);
                //设置支付状态
                order.setPayStatus("2");

                //根据订单号，修改订单的流水号，支付时间、支付状态
                orderService.updateById(order);
            }
        }


    }
}
